import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { courseApi } from '../api/course';
import { Link } from 'react-router-dom';

export function Courses() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('');

  const { data: response } = useQuery({
    queryKey: ['courses', searchTerm, selectedCategory],
    queryFn: () => courseApi.getCourses({
      search: searchTerm || undefined,
      category: selectedCategory || undefined
    }).then((res: any) => res.data),
  });

  const { data: categoriesResponse } = useQuery({
    queryKey: ['categories'],
    queryFn: () => courseApi.getCategories().then((res: any) => res.data),
  });

  const courses = response?.data || response;
  const categories = categoriesResponse?.data || categoriesResponse;

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">课程列表</h1>
      
      <div className="flex flex-col md:flex-row gap-4">
        <input
          type="text"
          placeholder="搜索课程..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="flex-1 px-4 py-2 border rounded-lg"
        />
        
        <select
          value={selectedCategory}
          onChange={(e) => setSelectedCategory(e.target.value)}
          className="px-4 py-2 border rounded-lg"
        >
          <option value="">所有分类</option>
          {categories?.map((category: string) => (
            <option key={category} value={category}>
              {category}
            </option>
          ))}
        </select>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {courses?.map((course: any) => (
          <div key={course.id} className="bg-white rounded-lg shadow hover:shadow-lg transition">
            <img 
              src={course.thumbnail || 'https://via.placeholder.com/300x200'} 
              alt={course.title}
              className="w-full h-48 object-cover rounded-t-lg"
            />
            <div className="p-4">
              <h3 className="font-semibold text-lg mb-2">{course.title}</h3>
              <p className="text-gray-600 text-sm mb-2">{course.description}</p>
              <div className="flex justify-between items-center">
                <span className="text-xl font-bold text-blue-600">
                  {course.price === 0 ? '免费' : `¥${course.price}`}
                </span>
                <Link 
                  to={`/courses/${course.id}`}
                  className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
                >
                  查看详情
                </Link>
              </div>
            </div>
          </div>
        ))}
      </div>

      {courses?.length === 0 && (
        <div className="text-center py-8">
          <p className="text-gray-500">没有找到相关课程</p>
        </div>
      )}
    </div>
  );
}